package com.example.vpnservicedemo.utils;

import android.net.VpnService;
import android.util.Log;

import org.pcap4j.packet.namednumber.IpVersion;

import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PrintUtil {


    public static void print(ByteBuffer byteBuffer) {
        StringBuilder sb = new StringBuilder();
        byte[] array = byteBuffer.array();
        //添加虚假连接层
        byte[] link = {12, -99, -110, 21, -29, 83, -56, 108, 32, -73, 23, 124, 8, 0};


        ByteBuffer buffer = ByteBuffer.allocate(array.length + link.length);
        buffer.put(link);
        buffer.put(array);
        byte[] newArray = buffer.array();


        for (int i = 0; i < newArray.length; i++) {

            if (i % 16 == 0) {
                sb.append(String.format("\r\n%04X    ", i));
            }
            sb.append(String.format("%02X ", newArray[i]));
        }
        Log.i("16进制", sb.toString());

    }

    public static StringBuilder print(byte[] fileContent) {

        // 添加当前时间戳
        long currentTimeMillis = System.currentTimeMillis();
        StringBuilder context = getContext(currentTimeMillis, fileContent);

        // 输出最终的字符串
        Log.i("print", context.toString());

        return context;
    }


    public static StringBuilder getContext(long time,byte[] fileContent){
        // 使用 StringBuilder 构建输出字符串
        StringBuilder outputBuffer = new StringBuilder();

        // 添加起始位置和数据链路层标识
        outputBuffer.append("\r\n+---------+---------------+----------+\r\n");


        String timestamp = new SimpleDateFormat("HH:mm:ss,SSS,000").format(new Date(time));
        outputBuffer.append(String.format("%s\tETHER\r\n", timestamp));

        // 添加每行的十六进制数据
        outputBuffer.append(String.format("|%d   |", 0));

        //添加虚假的链路层
        outputBuffer.append("00|1a|2b|3c|4d|5e|00|1a|2b|3c|4d|5e|");
        int ipVersion = (fileContent[0] >> 4) & 0x0f;
        if (ipVersion == IpVersion.IPV4.value().intValue()) {
            outputBuffer.append("08|00|");
        } else if (ipVersion == IpVersion.IPV6.value().intValue()) {
            outputBuffer.append("86|dd|");
        } else {
            outputBuffer.append("00|00|");
        }

        //添加网络层
        for (int i = 0; i < fileContent.length; i++) {
            outputBuffer.append(String.format("%02x|", fileContent[i]));
        }
        // 添加结束标记
        outputBuffer.append("\r\n");
//        outputBuffer.append("\r\n");

        return outputBuffer;
    }


}
